package com.itheima.health.controller.backend;

import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author deng
 * @package com.itheima.health.controller.backend
 * @date Created in 2024/7/15 08:28
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportService reportService;
    @Autowired
    private MemberService memberService;

    @RequestMapping("/getMemberReport.do")
    public Result getMemberReport() {
        // 1.获得当前日期之前的12个月的日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            list.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("months", list);

        try {
            List<Integer> memberCount = memberService.findMemberCountByMonth(list);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (ParseException e) {
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData.do")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReport();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出 运营统计数据到 Excel报表
     * @return
     */
    @RequestMapping("/exportBusinessReport.do")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = reportService.getBusinessReport();
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            String reportExcelPath = "/static/backend/template/report_template.xlsx";
            Class<?> clazz = ReportController.class; // 请替换为你的当前类
            URL reportUrl = clazz.getResource(reportExcelPath);
            String reportTemplateRealPath = reportUrl.getPath();
            System.out.println("reportTemplateRealPath = " + reportTemplateRealPath);
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(reportTemplateRealPath));
            XSSFSheet sheetAt0 = workbook.getSheetAt(0);
            sheetAt0.getRow(2).getCell(5).setCellValue(reportDate);
            sheetAt0.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheetAt0.getRow(4).getCell(7).setCellValue(totalMember);
            sheetAt0.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheetAt0.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            sheetAt0.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheetAt0.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheetAt0.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheetAt0.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheetAt0.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheetAt0.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            int rowNum = 12;
            for (Map setmeal : hotSetmeal) {
                String name = (String) setmeal.get("name");
                Long setmealCount = (Long) setmeal.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) setmeal.get("proportion");
                sheetAt0.getRow(rowNum).getCell(4).setCellValue(name);
                sheetAt0.getRow(rowNum).getCell(5).setCellValue(setmealCount);
                sheetAt0.getRow(rowNum).getCell(6).setCellValue(proportion.doubleValue());
                sheetAt0.getRow(rowNum).getCell(7).setCellValue(DateUtils.getTodayString());
                rowNum++;
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=everyones-health.xlsx");
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    @GetMapping("getSetmealReport.do")
    public Result getSetmealReport(){
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,reportService.getSetmealReport());
    }
}
